from geventwebsocket import WebSocketServer, WebSocketError
from flask import Flask, request, render_template
import upload as up
import Queue
import hashlib




slist = []
mque = Queue.deque(maxlen=10)
app = Flask(__name__)
#app.debug=True
@app.route('/')
def index():
    return render_template('index2.html')

@app.route('/chat')
def api():
    ws = request.environ.get('wsgi.websocket')
    print 'new client'
    print ws
    if not ws:
        abort(400, "Expected WebSocket request")
    slist.append(ws)
# when new ws clien conn it ,send old msg 
    send_old_msg(ws)
    while True:
        try:
            msg = ws.receive()
#exit will send a None type msg
            if msg is None or type(msg) is None:
                print 'exit::',msg
                slist.remove(ws)
                break
            print(msg)
            sendAll(msg,ws)
        except WebSocketError as err:
            # Possibility to execute code when connection is closed
#socket is dead
            print 'error:',format(err)
            slist.remove(ws)
            break
    return 'close'
#send old message
def send_old_msg(ws):
    for m in mque:
#       print m,m is None,type(m) is None
        ws.send(m)
def save_msg(m):
    mque.append(m)

@app.route('/upload',methods=['post'])
def img():
    f = request.files['img']
    f_name = f.filename
#   temp save path
    path = '/tmp/'+f_name
    try:
        f.save(path)
        #get md5 and save in txt&md5_dic
#       md5 as name
        f_name = md5(path)+'.'+f_name.split('.',2)[1]        
        up.qiniu_upload(path,f_name)
        print f_name+' save in qiniu'
#       when save success , put link in dic
    except Exception as err:
        print 'upload err',format(err)
        app.logger.error('upload img failed')
#       return defult pic 
        f_name = '50000.jpg'
#    name = request.form['username']
#    print 'user is,'+name
#    sendAll(name+':<img src="http://7xo1fz.com1.z0.glb.clouddn.com/'+f_name+'">','')
#   return '<img src="http://7xo1fz.com1.z0.glb.clouddn.com/'+f_name+'">'
    return 'http://7xo1fz.com1.z0.glb.clouddn.com/'+f_name
#getMd5
def md5(path):
    return hashlib.md5(open(path, 'rb').read()).hexdigest()

def sendAll(msg,w):
    save_msg(msg)
#    print(msg.value)
    for ws in slist:
        print ws,w
        if ws!=w:
            ws.send(msg)
if __name__ == '__main__':
    port = 8000
    print 'aaa'
    server = WebSocketServer(("", port), app)
    print 'ttt'
    server.serve_forever()
    print 'start'
